import React, { useState } from "react";
import { Upload } from "antd";
import { useMessage } from '@/hooks/useMessage';
import type { UploadProps } from "antd";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import type { RcFile } from "antd/es/upload/interface";
import { ossAPI } from "@/lib/api";

interface ImageUploadProps {
  value?: string;
  onChange?: (url: string) => void;
  maxSize?: number; // MB
  acceptTypes?: string[];
  uploadText?: string;
  width?: number;
  height?: number;
}

export default function ImageUpload({ value, onChange, maxSize = 10, acceptTypes = ["image/jpeg", "image/png"], uploadText = "上传", width = 80, height = 60 }: ImageUploadProps) {
  const message = useMessage();
  const [uploading, setUploading] = useState(false);

  const beforeUpload = (file: RcFile) => {
    const isValidType = acceptTypes.includes(file.type);
    if (!isValidType) {
      message.error(`只能上传 ${acceptTypes.join("/")} 格式的图片!`);
      return false;
    }

    const isValidSize = file.size / 1024 / 1024 < maxSize;
    if (!isValidSize) {
      message.error(`图片大小必须小于 ${maxSize}MB!`);
      return false;
    }

    return true;
  };

  type CustomRequestOptions = Parameters<Required<UploadProps>["customRequest"]>[0];

  const handleCustomRequest = async (options: CustomRequestOptions) => {
    const { file, onSuccess, onError } = options;
    setUploading(true);

    try {
      const res = await ossAPI.getSign();
      if (!res.success) {
        const error = new Error("获取上传签名失败");
        message.error("获取上传签名失败");
        if (onError) onError(error);
        return;
      }

      const { accessKeyId, policy, signature, dir, host } = res.data;
      const key = `${dir}${Date.now()}-${(file as RcFile).name}`;

      const formData = new FormData();
      formData.append("key", key);
      formData.append("policy", policy);
      formData.append("OSSAccessKeyId", accessKeyId);
      formData.append("success_action_status", "200");
      formData.append("signature", signature);
      formData.append("file", file);

      const uploadRes = await fetch(host, {
        method: "POST",
        body: formData,
      });

      if (uploadRes.ok) {
        const imageUrl = `${host}/${key}`;
        onChange?.(imageUrl);
        message.success("图片上传成功");
        if (onSuccess) {
          onSuccess({ url: imageUrl });
        }
      } else {
        throw new Error("上传失败");
      }
    } catch (err) {
      const error = err as Error;
      console.error("上传图片失败:", error);
      message.error("上传图片失败");
      if (onError) onError(error);
    } finally {
      setUploading(false);
    }
  };

  const uploadButton = (
    <div>
      {uploading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>{uploadText}</div>
    </div>
  );

  return (
    <Upload name='image' listType='picture-card' showUploadList={false} customRequest={handleCustomRequest} beforeUpload={beforeUpload} style={{ width, height }}>
      {value ? <img src={value} alt='上传的图片' style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : uploadButton}
    </Upload>
  );
}
